﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BuildHelper.Work.GUI;
using BuildHelper.Work.JAVA;
using ProgNetComponentsDx.Options;
using ProgNetComponentsDx.Browsers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using DevExpress.XtraTab;
using System.IO;
using DevExpress.XtraBars;

namespace BuildHelper.Work.Short
{
    public partial class ShortForm : ProgNetComponentsDx.Forms.HideToTrayForm
    {
        private BarMenuControl menuControl = new BarMenuControl();

        private static bool isFirst = true;
        public static bool PauseDeactive
        {
            get;
            set;
        }

        private static ShortForm _Instance;
        public static ShortForm Instance
        {
            get { return _Instance; }
        }

        public static void ShowForm()
        {
            if (_Instance == null)
            {
                _Instance = new ShortForm();
            }
            if (isFirst)
            {
                isFirst = false;
                _Instance.Left = Screen.PrimaryScreen.WorkingArea.Width - _Instance.Width + Screen.PrimaryScreen.WorkingArea.X;
                _Instance.Top = Screen.PrimaryScreen.WorkingArea.Height - _Instance.Height + Screen.PrimaryScreen.WorkingArea.Y;
            }
            if (_Instance.CanShow())
            {
                _Instance.Show();
                User32.SetActiveWindow(_Instance.Handle);
            }
        }

        public static void CloseInstance()
        {
            if (_Instance != null)
                _Instance.Close();
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            OptionCache.OptionChanged -= new OptionChangedEventHandler(OptionCache_OptionChanged);
            Setup.Brancze.BranczeTools.ActiveBranchChanged -= new EventHandler(BranczeTools_ActiveBranchChanged);
  
            if (isHidden)
            {
                Visible = false;
                Location = _Instance.prevLocation;
                Size = _Instance.prevSize;
            }
            foreach (var kvp in guiPages)
                (kvp.Value.Controls[0] as ShortGuiControl).SaveLayout();

            operacjeNaPlikachControl1.SaveAll();
            layoutProvider1.SaveLayout();
            _Instance = null;
           
        }
       
        private bool CanShow()
        {
            foreach (XtraTabPage p in tabControl.TabPages)
                if (p.PageVisible)
                    return true;
            return false;
        }
        #region Gui
        private static Dictionary<BudowanieGui, XtraTabPage> guiPages = new Dictionary<BudowanieGui, XtraTabPage>();

        public static void AddGuiForm(GUI.BudowanieGui form)
        {
            if (_Instance != null)
                _Instance._GuiEnable(form, true);
        }
        public static void RemoveGuiForm(GUI.BudowanieGui form)
        {
            if (_Instance != null)
                _Instance._GuiEnable(form, false);
        }
        private void _GuiEnable(BudowanieGui form, bool add)
        {
            if (add)
            {
                if (!guiPages.ContainsKey(form))
                {
                    XtraTabPage p = new XtraTabPage();
                    p.Text = "GUI";
                    if (form.Pojedyncza)
                        p.Text += " [" + form.Brancz + "]";
                    ShortGuiControl gc = new ShortGuiControl();
                    gc.GuiForm = form;
                    gc.Dock = DockStyle.Fill;
                    p.Controls.Add(gc);
                    p.PageVisible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Gui);
                    this.tabControl.TabPages.Add(p);
                    form.FormClosed += new FormClosedEventHandler(guiform_FormClosed);
                    guiPages.Add(form, p);
                }
            }
            else
            {
                if(guiPages.ContainsKey(form))
                {
                    tabControl.TabPages.Remove(guiPages[form]);
                    guiPages.Remove(form);
                }
            }
        }

        public static void GuiSetCurrentStm(BudowanieGui form, string stm)
        {
            if (_Instance != null)
            {
                if (guiPages.ContainsKey(form))
                    (guiPages[form].Controls[0] as ShortGuiControl).SetCurrentStm(stm);
            }
        }
        public static void GuiPoczatekBudowania(BudowanieGui form)
        {
            IsBuilding++;
            if (guiPages.ContainsKey(form))
                (guiPages[form].Controls[0] as ShortGuiControl).PoczatekBudowania();
        }
        public static void GuiKoniecBudowania(BudowanieGui form)
        {
            IsBuilding--;
            if (guiPages.ContainsKey(form))
                (guiPages[form].Controls[0] as ShortGuiControl).KoniecBudowania();
        }
        public static void GuiSetProgressTest(BudowanieGui form, string text)
        {
            if (guiPages.ContainsKey(form))
                (guiPages[form].Controls[0] as ShortGuiControl).SetProgressTest(text);
        }
        static void guiform_FormClosed(object sender, FormClosedEventArgs e)
        {
            RemoveGuiForm(sender as BudowanieGui);
        }
        #endregion
        #region Java
        private static Dictionary<BudowanieJavy, XtraTabPage> javaPages = new Dictionary<BudowanieJavy, XtraTabPage>();

        public static void AddJavaForm(JAVA.BudowanieJavy form)
        {
            if (_Instance != null)
                _Instance._JavaEnable(form, true);
        }
        public static void RemoveJavaForm(JAVA.BudowanieJavy form)
        {
            if (_Instance != null)
                _Instance._JavaEnable(form, false);
        }
        private void _JavaEnable(BudowanieJavy form, bool add)
        {
            if (add)
            {
                if (!javaPages.ContainsKey(form))
                {
                    XtraTabPage p = new XtraTabPage();
                    p.Text = "Java";
                    if (form.Pojedyncza)
                        p.Text += " [" + form.Brancz + "]";
                    ShortJavaControl gc = new ShortJavaControl();
                    gc.Form = form;
                    gc.Dock = DockStyle.Fill;
                    p.Controls.Add(gc);
                    p.PageVisible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Java);
                    this.tabControl.TabPages.Add(p);
                    form.FormClosed += new FormClosedEventHandler(javaform_FormClosed);
                    javaPages.Add(form, p);
                }
            }
            else
            {
                if (javaPages.ContainsKey(form))
                {
                    tabControl.TabPages.Remove(javaPages[form]);
                    javaPages.Remove(form);
                }
            }
        }

        public static void JavaPoczatekBudowania(BudowanieJavy form)
        {
            IsBuilding++;
            if (javaPages.ContainsKey(form))
                (javaPages[form].Controls[0] as ShortJavaControl).PoczatekBudowania();
        }
        public static void JavaKoniecBudowania(BudowanieJavy form)
        {
            IsBuilding--;
            if (javaPages.ContainsKey(form))
                (javaPages[form].Controls[0] as ShortJavaControl).KoniecBudowania();
        }
        //public static void JavaSetProgressTest(string text)
        //{
        //    _Instance.shortJavaControl1.SetProgressTest(text);
        //}
        static void javaform_FormClosed(object sender, FormClosedEventArgs e)
        {
            RemoveJavaForm(sender as BudowanieJavy);
        }
        #endregion
        
        public static void ShowByDefault()
        {
            if (_Instance == null)
                _Instance = new ShortForm();

            if (_Instance != null)
                _Instance.ShowDefault();
        }
        private ShortForm()
        {
            InitializeComponent();
            menuControl.LayoutLoaded += new EventHandler(menuControl_LayoutLoaded);
            menuControl.Initialize(this);
            notesControl1 = new NotesControl();
            notesControl1.File = Application.StartupPath + "\\Notatki.rtf";
            notesControl1.Dock = DockStyle.Fill;
            notesControl1.InitControl();
            tabNotes.Controls.Add(notesControl1);

            operacjeNaPlikachControl1 = new OperacjeNaPlikachControl();
            operacjeNaPlikachControl1.Dock = DockStyle.Fill;
            this.operacjeNaPlikachControl1.AutoScroll = true;
            tabOperacjeNaPlikach.Controls.Add(operacjeNaPlikachControl1);
            operacjeNaPlikachControl1.InitControl();
        }

        void menuControl_LayoutLoaded(object sender, EventArgs e)
        {
            UpdateBarMenu();
        }

        public void ShowDefault()
        {
            if (CanShow())
            {
                if (!userClosed && OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.OtworzSkrotyGdyMozliwe))
                {
                    ShowForm();
                }
            }
        }
        private bool userClosed = false;

        protected override void OnLoad(EventArgs e)
        {
            ShowInTaskbar = false;
           

            base.OnLoad(e);
            if (!this.IsDesignMode())
            {
                tabControl.SetTabMinSize(40);
                lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
                OptionCache.OptionChanged += new OptionChangedEventHandler(OptionCache_OptionChanged);
                Setup.Brancze.BranczeTools.ActiveBranchChanged += new EventHandler(BranczeTools_ActiveBranchChanged);
                OptionCache_OptionChanged(null);
                BranczeTools_ActiveBranchChanged(null, null);
                ceTylkoLokalne_CheckedChanged(null, null);
            }
            userClosed = false;
        }

        private static uint WS_POPUP = 0x80000000;
        // private static uint WS_EX_TOPMOST = 0x00000008;
        private static uint WS_EX_TOOLWINDOW = 0x00000080;

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= unchecked((int)WS_POPUP);
                cp.ExStyle |= (int)WS_EX_TOOLWINDOW;
                return cp;
            }
        }

        private static int _IsBuilding;
        public static int IsBuilding
        {
            get { return _IsBuilding; }
            set
            {
                if (value > -1)
                {
                    _IsBuilding = value;
                    if (value == 0)
                    {
                        if (!_Instance.IsActive)
                            _Instance.OnDeactivate(EventArgs.Empty);
                    }
                }
            }
                
        }

        void BranczeTools_ActiveBranchChanged(object sender, EventArgs e)
        {
            lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
            lueBranczSvn.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
        }

        void OptionCache_OptionChanged(object optionId)
        {
            bool showDef = false;
            if (optionId == null ||
                Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseProc.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.TortoiseProc.IsTheSameKey(optionId))
            {
                tabTortoise.PageVisible = GlobalTools.TortoiseTools.CheckTortoiseProc(false) && OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.TortoiseProc);
                showDef = true;
            }

            if (optionId == null ||
                Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.TortoiseSvn.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Rozne_Group.Skroty.KopiujLogDoSchowka.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Rozne_Group.Skroty.ZapisujLog.IsTheSameKey(optionId))
            {
                tabTortoiseSvn.PageVisible = GlobalTools.TortoiseTools.CanUseTortoiseSvn() && 
                    OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.TortoiseSvn) && 
                    (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.ZapisujLog) ||
                     OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.KopiujLogDoSchowka));
                showDef = true;
            }

            if (optionId == null ||
                Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile.IsTheSameKey(optionId))
            {
                logFile = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile);
                showDef = true;
            }

            if (optionId == null ||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Java.IsTheSameKey(optionId))
            {
                foreach(var kvp in javaPages)
                kvp.Value.PageVisible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Java);
                showDef = true;
            }

            if (optionId == null ||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Gui.IsTheSameKey(optionId))
            {
                foreach (var kvp in guiPages)
                    kvp.Value.PageVisible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Gui);
                showDef = true;
            }

            if (optionId == null ||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Notes.IsTheSameKey(optionId))
            {
                tabNotes.PageVisible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.Notes);
                showDef = true;
            }
            if (optionId == null ||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.OperacjeNaPlikach.IsTheSameKey(optionId))
            {
                tabOperacjeNaPlikach.PageVisible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Formy.OperacjeNaPlikach);
                showDef = true;
            }
            if (Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Menu.Custom.IsTheSameKey(optionId)||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Menu.GlowneMenu.IsTheSameKey(optionId)||
                Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Menu.Status.IsTheSameKey(optionId))
            {
                UpdateBarMenu();
            }
            if (showDef)
                ShowDefault();
        }

        private void UpdateBarMenu()
        {
            menuControl.BarManager.MainMenu.Visible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Menu.GlowneMenu);
            menuControl.BarManager.StatusBar.Visible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Menu.Status);
            menuControl.BarManager.StatusBar.OptionsBar.DisableClose = true;

            bool customVisible = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Menu.Custom);

            foreach (Bar c in menuControl.BarManager.Bars)
            {
                if (c != menuControl.BarManager.MainMenu && c != menuControl.BarManager.StatusBar)
                    c.Visible = customVisible;
                c.OptionsBar.DisableClose = true;
            }
        }

        private bool shown = false;
        void layoutProvider1_LayoutLoaded(object sender, System.EventArgs e)
        {
            if (!shown)
            {
                shown = true;
                prevLocation = Location;
                prevSize = Size;

                isHidden = true;
                ShortForm_HidingToTray(this, c);
            }
        }

        #region TortoiseProc
        private void RunTortoise(string command, bool addUrl = false, bool useApps = false)
        {
            if (ceTylkoLokalne.Checked)
            {
                GlobalTools.TortoiseTools.RunTortoise(lueBrancz.EditValue.AsString(), command, addUrl, useApps);
            }
            else
            {
                GlobalTools.TortoiseTools.RunTortoiseGlobal(lueBrancz.EditValue.AsString(), command, "", true);
            }
        }
        private void btnCheckOutTortoise_Click(object sender, EventArgs e)
        {
            if (ceTylkoLokalne.Checked)
                RunTortoise("checkout", true);
            else
                this.ShowDxWarningDialog("Wybierz brancza lokalnego");
        }

        private void btnUpdateTortoise_Click(object sender, EventArgs e)
        {
            if (ceTylkoLokalne.Checked)
                RunTortoise("update");
            else
                this.ShowDxWarningDialog("Wybierz brancza lokalnego");
        }

        private void btnLogTortoise_Click(object sender, EventArgs e)
        {
            string command = "log";
            string rev = teRevTortoiseProc.Text;
            if (rev.IsNotNullOrEmpty())
                command += " /startrev:" + rev + " /endrev:" + rev;
            
            RunTortoise(command, useApps: OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise.DirForLog) == "A");
        }

        private void btnZmianyTortoise_Click(object sender, EventArgs e)
        {
            if (ceTylkoLokalne.Checked)
                RunTortoise("repostatus", useApps: OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise.DirForZmiany) == "A");
            else
                this.ShowDxWarningDialog("Wybierz brancza lokalnego");
        }

        private void btnCleanupTortoise_Click(object sender, EventArgs e)
        {
            if (ceTylkoLokalne.Checked)
                RunTortoise("cleanup");
            else
                this.ShowDxWarningDialog("Wybierz brancza lokalnego");
        }
        private void btnCommitTortoise_Click(object sender, EventArgs e)
        {
            if (ceTylkoLokalne.Checked)
            {
                if (lueBrancz.EditValue.IsNotNull())
                    GlobalTools.TortoiseTools.Commit(lueBrancz.EditValue.AsString());
                else
                    this.ShowDxInfoDialog("Wybierz brancza");
            }
            else
                this.ShowDxWarningDialog("Wybierz brancza lokalnego");
        }
        #endregion
        #region tortoise svn

        Process procLogi;
        bool procLogiAdd = false;
        string log = "";
        string logFile = "";
        string lastRev = "";
        string rev = "";
        private void btnLogToClipboard_Click(object sender, EventArgs e)
        {
            if (procLogi != null)
            {
                this.ShowDxErrorDialog("Operacja w toku");
                return;
            }
            string brancz = lueBranczSvn.EditValue.AsString();
            rev = teRewizjaLogi.EditValue.AsString();
            if (brancz.IsNull())
            {
                this.ShowDxErrorDialog("Wybierz brancza");
                return;
            }

            if (rev.IsNull())
            {
                this.ShowDxErrorDialog("Podaj rewizję");
                return;
            }
            
            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, brancz);
            string path = "";
            if (r == null)
            {
                this.ShowDxErrorDialog("Nie można odnaleźć brancza " + brancz);
                return;
            }
            if (!GlobalTools.TortoiseTools.CanUseTortoiseSvn())
            {
                this.ShowDxErrorDialog("Brak svn. Sprawdź opcje.\n" +
                    GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn));
                return;
            }
            if (rev == lastRev)
            {
                FormMain.ShowWarningAlert("Log dla rwizji " + lastRev + " był już tworzony.");
                return;
            }
            
            path = r["URL"].AsString();
            procLogi = GlobalTools.CreateCMDProcess(procLogi_Data);

            string cmd = "svn log " + path + " -r " + rev + " --incremental --verbose ";
            procLogiAdd = false;
            log = "";
            progressLogi.Properties.Stopped = false;
            procLogi.EchoOff();
            GlobalTools.TortoiseTools.AddSvnToPath(procLogi);
            procLogi.Execute(cmd);
            procLogi.Echo("exit");
        }
        private void procLogiFinish(bool isLogi = true)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<bool>(procLogiFinish), isLogi);
                return;
            }
            procLogiAdd = false;

            try
            {
                if (procLogi != null)
                {
                    procLogi.CallExit();
                    procLogi.KillProcessTree();
                    procLogi.Dispose();
                }
            }
            catch { }
            procLogi = null;
            progressLogi.Properties.Stopped = true;
            if (isLogi)
            {
                if (log.IsNotNull())
                {
                    lastRev = rev;

                    bool clip = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.KopiujLogDoSchowka);
                    bool zapisz = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.ZapisujLog);

                    if (clip)
                        Clipboard.SetText(log);

                    if (zapisz)
                        zapisz = AddLogi();
                    if (zapisz)
                    {
                        if (clip)
                            FormMain.ShowInfoAlert("Log zapiszany w schowku i pliku.");
                        else
                            FormMain.ShowInfoAlert("Log zapiszany w pliku.");
                    }
                    else if (clip)
                    {
                        FormMain.ShowInfoAlert("Log zapiszany w schowku.");
                    }
                    log = "";
                }
                else
                {
                    FormMain.ShowWarningAlert("Brak logu.\nSprawdź brancz i rewizję.");
                }
            }
        }
        private bool AddLogi()
        {
            if (logFile.IsNullOrEmpty())
            {
                this.ShowDxErrorDialog("Brak pliku. Sprawdź opcje.\n"
                    + GlobalTools.GetOptionPath(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile));
                return false;
            }
            log = log + Constants.NewLineLinux;
            log.AppendToFile(logFile);
            return true;
        }
        private void procLogi_Data(object sender, DataReceivedEventArgs e)
        {
            string msg = e.Data.AsString();
            if (msg.XMatch("^echo exit"))
                procLogiFinish();
            else if (procLogiAdd)
            {
                log = log.AppendLine(msg);
            }
            else if (msg.XMatch("svn log"))
            {
                procLogiAdd = true;
            }
        }

        private void teRewizjaLogi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnLogToClipboard.PerformClick();
        }
        #endregion

        public new void Show()
        {
            isHidden = true;
            ShortForm_HidingToTray(this, c);
            base.Show();
            UpdateBarMenu();
        }
        bool isHidden = false;
        private Size prevSize = new Size();
        private Point prevLocation = Point.Empty;

        private void ShortForm_HidingToTray(object sender, CancelEventArgs e)
        {
            this.Region = new Region(new Rectangle(0,0,0,0));

            bool tmp = PauseDeactive;
            PauseDeactive = true;
            
            PauseDeactive = tmp;
            e.Cancel = true;
            isHidden = !isHidden;
            this.Text = "Skróty";
           
            if (isHidden)
            {
                prevSize = Size;
                prevLocation = Location;
                tabControl.Visible = false;
                pictureEdit1.Location = new System.Drawing.Point(1, 1);
                Rectangle r = new Rectangle();
                int add = 0;
                string type = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Skroty.Zwijanie);
                Point p = new Point(4 + pictureEdit1.Left, 24 + pictureEdit1.Top);
                switch (type)
                {
                    case "MI":
                        pictureEdit1.Size = new Size(24, 24);
                        goto case "Icon";
                    case "DI":
                        pictureEdit1.Size = new Size(48, 48);
                        goto case "Icon";
                    case "Icon":
                        r = new Rectangle(p, pictureEdit1.Size);
                        break;
                    default:
                        r.Width = 132;
                        r.Height = 25;
                        r.Y = 0;
                        r.X = 0;
                        this.MinimumSize = r.Size;
                        this.Size = r.Size;
                        break;
                }

                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                string dokowanie = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Skroty.MinimalizujDo);
                int Left = 0;
                int Top = 0;
                
                switch (dokowanie)
                {
                    case "PD":
                        Left = Screen.PrimaryScreen.WorkingArea.Width - r.Width - r.X + Screen.PrimaryScreen.WorkingArea.X - add;
                        Top = Screen.PrimaryScreen.WorkingArea.Height - r.Height - r.Y + Screen.PrimaryScreen.WorkingArea.Y - add;
                        this.Location = new Point(Left, Top);
                        break;
                    case "LD":
                        Left = Screen.PrimaryScreen.WorkingArea.X - r.X + add;
                        Top = Screen.PrimaryScreen.WorkingArea.Height - r.Height - r.Y + Screen.PrimaryScreen.WorkingArea.Y - add;
                        this.Location = new Point(Left, Top);
                        break;
                    case "PG":
                        Left = Screen.PrimaryScreen.WorkingArea.Width - r.X -r.Width + Screen.PrimaryScreen.WorkingArea.X - add;
                        Top = Screen.PrimaryScreen.WorkingArea.Y - r.Y + add;
                        this.Location = new Point(Left, Top);
                        break;
                    case "LG":
                        Left = Screen.PrimaryScreen.WorkingArea.X  - r.X + add;
                        Top = Screen.PrimaryScreen.WorkingArea.Y - r.Y + add;
                        this.Location = new Point(Left, Top);
                        break;
                    case "PGRF":
                        Left = prevLocation.X + prevSize.Width - r.Width;
                        Top = prevLocation.Y - r.Y;
                        this.Location = new Point(Left, Top);
                        break;
                    case "LDRF":
                        Left = prevLocation.X - r.X;
                        Top = prevLocation.Y + prevSize.Height - r.Height - r.Y;
                        this.Location = new Point(Left, Top);
                        break;
                    case "PDRF":
                        Left = prevLocation.X + prevSize.Width - r.Width -r.X;
                        Top = prevLocation.Y + prevSize.Height - r.Height -r.Y;
                        this.Location = new Point(Left, Top);
                        break;
                    case "CF":
                        Left = prevLocation.X + (prevSize.Width - r.Width) / 2 - r.X;
                        Top = prevLocation.Y + (prevSize.Height - r.Height) / 2 - r.Y;
                        this.Location = new Point(Left, Top);
                        break;
                    default:
                        this.Location = new Point(this.Left - p.X, this.Top - p.Y);
                        //Left = Left + Width - r.Width;
                        //Top = Top + Height - r.Height;
                        break;
                }
                pictureEdit1.Visible = isHidden;
                this.Region = new Region(r);
            }
            else
            {
                tabControl.Visible = true;
                pictureEdit1.Visible = isHidden;
                pictureEdit1.Location = new Point(-100, -100);
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                this.Refresh();
                if (!prevLocation.IsEmpty)
                    this.Location = prevLocation;
                
                this.Size = prevSize;
                
                this.Region = null;
                this.MinimumSize = new Size(339, 310);
            }
        }

        CancelEventArgs c = new CancelEventArgs();
        private bool IsActive;
       
        protected override void OnActivated(EventArgs e)
        {
            this.Opacity = 1.0;
            IsActive = true;
            base.OnActivated(e);
            if (isHidden)
                ShortForm_HidingToTray(this, c);
        }
        protected override void OnDeactivate(EventArgs e)
        {
            base.OnDeactivate(e);
            if (PauseDeactive)
                return;
            IsActive = false;
            bool hide = false;
            bool changeVisibility = true;
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.ZwinPrzyDeaktywacji))
            {
                if (!isHidden)
                {
                    hide = true;
                    if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.NieMinimalizujPodczasBudowania) &&
                        IsBuilding >0)
                        hide = false;
                    if (tabControl.SelectedTabPage == tabNotes && OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Notes.NieMinimalizujGdyWidocznyNotes))
                        hide = false;
                }
            }
            if (hide)
            {
                ShortForm_HidingToTray(this, c);
            }
            if (isHidden && !OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.ZmieniajWidocznoscGdyZwiniete))
                changeVisibility = false;
            if (!isHidden && tabControl.SelectedTabPage == tabNotes && OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Notes.NieZmieniajWidocznosciGdyWidocznyNotes))
                changeVisibility = false;

            if (changeVisibility)
            {
                this.Opacity = OptionCache.GetOptionValue(Init.InitFormOptionNames.Rozne_Group.Skroty.WidocznoscGdyNieaktywne).AsDouble();
            }
            else
            {
                this.Opacity = 1.0;
            }
        }

        const int WM_ACTIVATE = 0x0006;
        const int WA_INACTIVE = 0;
        const int WA_ACTIVE = 1;
        const int WA_CLICKACTIVE = 2;


        const int WM_INITMENUPOPUP = 0x117;
        [DllImport("user32.dll")]
        static extern bool EndMenu();
       
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_ACTIVATE:
                    if (m.WParam.AsInt() == WA_INACTIVE)
                    {
                        PauseDeactive = false;
                        try
                        {
                            Control f = Form.FromHandle(m.LParam);
                            if (f is ProgNetComponentsDx.Browsers.BrowserForm ||
                                f is DevExpress.XtraBars.Customization.CustomizationForm ||
                                f is DevExpress.XtraGrid.Views.Grid.Customization.CustomizationForm)
                            {
                                PauseDeactive = true;
                                (f as Form).FormClosed -= new FormClosedEventHandler(ShortForm_FormClosed);
                                (f as Form).FormClosed += new FormClosedEventHandler(ShortForm_FormClosed);
                            }
                           
                            //if (f is DevExpress.XtraGrid.Views.Grid.Customization.CustomizationForm)
                            //{
                            //    if ((f as DevExpress.XtraGrid.Views.Grid.Customization.CustomizationForm).GridControl != null &&
                            //        (f as DevExpress.XtraGrid.Views.Grid.Customization.CustomizationForm).GridControl.FindForm() == this)
                            //    {
                            //        PauseDeactive = true;
                            //    }
                            //}
                        }
                        catch { }
                    }
                    break;
                case WM_INITMENUPOPUP:
                //case WM_ENTERMENULOOP:
                    base.WndProc(ref m);
                    EndMenu();
                    return;
                case 0x112://WM_SYSCOMMAND
                    if ((int)(m.WParam) == 0xf063)//SC_CLOSEDOUBLECLICK
                        return;
                    break;
            }
            base.WndProc(ref m);
        }

        void ShortForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.TopMost = true;
            (sender as Form).FormClosed -= new FormClosedEventHandler(ShortForm_FormClosed);
        }

        private void ceTylkoLokalne_CheckedChanged(object sender, EventArgs e)
        {
            string old = lueBrancz.EditValue.AsString();
            browserProvider1.GetSettings(lueBrancz).BeginSettings();
            if (ceTylkoLokalne.Checked)
            {
                browserProvider1.GetSettings(lueBrancz).BrowserId = Init.InitFormBrowserNames.Setup.BranczeAktywne;
                browserProvider1.GetSettings(lueBrancz).AdditionalBrowserId = Init.InitFormBrowserNames.Setup.Brancze;
                browserProvider1.GetSettings(lueBrancz).AdditionalBrowserDisplayType = BrowserSettingsDisplayType.DialogWindow; 
                browserProvider1.GetSettings(lueBrancz).AddBrowserDialogButton = false;
            }
            else
            {
                browserProvider1.GetSettings(lueBrancz).BrowserId = Init.InitFormBrowserNames.Statyczne.BranczeSVN;
                browserProvider1.GetSettings(lueBrancz).AddBrowserDialogButton = true;
                browserProvider1.GetSettings(lueBrancz).AdditionalBrowserId = null;
            }
            browserProvider1.GetSettings(lueBrancz).EndSettings();

            if (BrowserCache.IsValid(browserProvider1.GetSettings(lueBrancz).BrowserId, true, old) ||
                (browserProvider1.GetSettings(lueBrancz).AdditionalBrowserId != null &&
                    BrowserCache.IsValid(browserProvider1.GetSettings(lueBrancz).AdditionalBrowserId, true, old)))
            {
                lueBrancz.EditValue = old;
            }
        }

        private void btnPatch_Click(object sender, EventArgs e)
        {
            if (procLogi != null)
            {
                this.ShowDxErrorDialog("Operacja w toku");
                return;
            }
            string brancz = lueBranczSvn.EditValue.AsString();
            rev = teRewizjaLogi.EditValue.AsString();
            if (brancz.IsNull())
            {
                this.ShowDxErrorDialog("Wybierz brancza");
                return;
            }

            if (rev.IsNull())
            {
                this.ShowDxErrorDialog("Podaj rewizję");
                return;
            }

            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, brancz);
            string path = "";
            if (r == null)
            {
                this.ShowDxErrorDialog("Nie można odnaleźć brancza " + brancz);
                return;
            }
            string svn = "";
            if (!GlobalTools.TortoiseTools.CanUseTortoiseSvn())
            {
                this.ShowDxErrorDialog("Brak svn. Sprawdź opcje.\n" +
                    GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn));
                return;
            }
            svn = GlobalTools.TortoiseTools.GetTortoiseSvnPath();

            path = r["URL"].AsString();

            int prevRev = rev.AsInt() - 1;
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                procLogi = GlobalTools.CreateCMDProcess(procLogi_DataPatch);
                string cmd = "svn diff " + " -r " + prevRev + ":" + rev + " " + path + " > " + saveFileDialog1.FileName.AddDoubleQuotes();
                procLogiAdd = false;
                progressLogi.Properties.Stopped = false;
                procLogi.EchoOff();
                GlobalTools.TortoiseTools.AddSvnToPath(procLogi);
                procLogi.Execute(cmd);
                procLogi.Echo("exit");
            }
        }

        private void procLogi_DataPatch(object sender, DataReceivedEventArgs e)
        {
            string msg = e.Data.AsString();
            if (msg.XMatch("^echo exit"))
            {
                FormMain.ShowInfoAlert("Patch zapisany");
                procLogiFinish(false);
            }
        }

        private void pictureEdit1_MouseDown(object sender, MouseEventArgs e)
        {
            OnActivated(EventArgs.Empty);
        }

    }
}
